package com.example.mobile203zlw20216061300511;

import android.os.Build;
import android.os.Bundle;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {
    String urL = "http://192.168.56.1:3000/posts";
    private TextView tv;
    String stv="";
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        new Thread(){
            public void run(){
              super.run();
                try {
                    URL url = new URL(urL);
                    HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
                    httpURLConnection.setRequestMethod("GET");//get访问方式
                    httpURLConnection.setConnectTimeout(3000);//以毫秒为单位，如果访问超时
                    InputStream inputStream = httpURLConnection.getInputStream();//字节保存
                    InputStreamReader inputStreamReader = new InputStreamReader(inputStream);//转换为字符
                    BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
                    String line=null;
                    while ((line=bufferedReader.readLine())!=null){
                        stv+=line;
                        stv+="\n";
                    }
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            tv.setText(stv);
                        }
                    });
                    bufferedReader.close();
                    inputStream.close();
                    inputStreamReader.close();
                    httpURLConnection.disconnect();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            };
        }.start();
    }

    private void initView() {
        tv = (TextView) findViewById(R.id.tv);

    }
}